package com.haha.http.rpc.common.util;

import com.haha.http.rpc.common.trace.TraceContextHolder;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @AUTHOR zhangxiaofan07
 * @CREATE 2022-01-28 11:50
 */
public class TraceUtils {
    private static final String PREFIX = "%s%s%07d";
    private static String IP_ADDRESS; //0b253296

    static {
        // 将ip地址转换为8位16进制数
        try {
            StringBuilder strBuilder = new StringBuilder();
            String tmp;
            String hostAddressStr = InetAddress.getLocalHost().getHostAddress();
            for (String str : hostAddressStr.split("\\.")) {
                tmp = Integer.toHexString(Integer.parseInt(str));
                if (tmp.length() == 1) {
                    strBuilder.append("0");
                }
                strBuilder.append(tmp);
            }
            IP_ADDRESS = strBuilder.toString();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    public static void generateTraceId() {
        String dateStr = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmssSSS");
        int randomInt = ThreadLocalRandom.current().nextInt(10000000);
        String traceId = String.format(PREFIX, dateStr, IP_ADDRESS, randomInt);
        TraceContextHolder.setTraceId(traceId);
    }
}
